package com.cti.ftpservice.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;


public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static
    {
        try
        {
           /* Configuration cfg = new Configuration().configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);*/
            
        	
            sessionFactory = SpringContextUtil.getBeanById("sessionFactory");  
        }
        catch (Throwable e)
        {
            throw new ExceptionInInitializerError(e);
        }
    }
 
    private HibernateUtil()
    {
    }

    public static final ThreadLocal threadLocal =new ThreadLocal(); 
    
    public static Session getCurrentSession(){
    	Session s = (Session) threadLocal.get();
    	 if(s == null) {  
    		 s = sessionFactory.openSession();
    		 threadLocal.set(s);   
    	 }
    	 return s;
    }
    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }
    public static void closeCurrentSession(){
    	Session s = (Session) threadLocal.get();
   	 	if(s != null) {  
   		 s.close();
   	 	
   	 	}
   	  threadLocal.set(null);
    }
}
